package com.lmk.mkcc.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.lmk.mkcc.CourseDoc;
import com.lmk.mkcc.domain.*;
import com.lmk.mkcc.dto.CourseSaveDto;
import com.lmk.mkcc.dto.CourseSendMessageDto;
import com.lmk.mkcc.dto.UserSmsDto;
import com.lmk.mkcc.enums.GlobalErrorCode;
import com.lmk.mkcc.feign.CourseEsService;
import com.lmk.mkcc.feign.GetMediaFileService;
import com.lmk.mkcc.feign.UserService;
import com.lmk.mkcc.mapper.*;
import com.lmk.mkcc.result.JSONResult;
import com.lmk.mkcc.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.lmk.mkcc.util.AssertUtil;
import com.lmk.mkcc.vo.CourseDetailVo;
import com.lmk.mkcc.vo.CourseInfoVo;
import com.lmk.mkcc.vo.CourseOrderVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author kun
 * @since 2022-09-30
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {
    @Autowired
    private ITeacherService teacherService;

    @Autowired
    private ICourseDetailService courseDetailService;
    @Autowired
    private ICourseMarketService courseMarketService;
    @Autowired
    private ICourseResourceService courseResourceService;
    @Autowired
    private ICourseSummaryService courseSummaryService;
    @Autowired
    private ICourseChapterService courseChapterService;
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private ICourseTypeService courseTypeService;
    @Autowired // 注入es的feign接口,将信息保存在es中
    private CourseEsService courseEsService;
    @Autowired
    private ICourseCollectService courseCollectService;
    @Autowired // 注入user的feign接口。查询user对象集合
    private UserService userService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private GetMediaFileService getMediaFileService;


    @Override
    public void save(CourseSaveDto courseSaveDto) {
        Course course = courseSaveDto.getCourse();
        CourseDetail courseDetail = courseSaveDto.getCourseDetail();
        CourseMarket courseMarket = courseSaveDto.getCourseMarket();
        CourseResource courseResource = courseSaveDto.getCourseResource();
        List<Long> teacharIds = courseSaveDto.getTeacharIds();
        //判断课程是否存在
        Course course1 = selectByName(course.getName());
        AssertUtil.isNull(course1, GlobalErrorCode.COURSE_EXISTENCE_ERROR);
        // 保存到数据库
        Long courseId= add(course,teacharIds);
        // 保存到课程详情
        courseDetail.setId(courseId);
        courseDetailService.insert(courseDetail);
        // 保存到销售表
        courseMarket.setId(courseId);
        courseMarketService.insert(courseMarket);
        // 保存到资源表
        courseResource.setCourseId(courseId);
        courseResourceService.insert(courseResource);
        // 初始化课程统计
        CourseSummary courseSummary = new CourseSummary();
        courseSummary.setId(courseId);
        courseSummaryService.insert(courseSummary);
        // 保存到中间表
        courseMapper.AddCourseTeacher(courseId,teacharIds);
        // 修改课程类型中的类型数量
        Long courseTypeId = course.getCourseTypeId();
        courseMapper.updatypecount(courseTypeId);

    }
    // 课程上架
    @Override
    public void onLineCourse(Long id) {
        Course course = selectById(id);
        // 判断课程是否存在
        AssertUtil.isNotNull(course,GlobalErrorCode.COURSE_NULL_ERROR);

        // 把课程的状态修改为上线
        course.setStatus(Course.on_status);
        // 设置上线时间
        course.setOnlineTime(new Date());
        // 保存到course表
        updateById(course);


        CourseDoc courseDoc = new CourseDoc();
        // 获取courseMarket信息
        CourseMarket courseMarket = courseMarketService.selectById(id);
        // 获取courseSummary信息
        CourseSummary courseSummary = courseSummaryService.selectById(id);
        // 获取coursetype表信息
        CourseType courseType = courseTypeService.selectById(course.getCourseTypeId());
        // 使用工具类进行拷贝
        BeanUtils.copyProperties(course,courseDoc);
        BeanUtils.copyProperties(courseMarket,courseDoc);
        BeanUtils.copyProperties(courseSummary,courseDoc);
        courseDoc.setTypeName(courseType.getName());
        String charge = courseMarket.getCharge() == 1?"免费":"收费";
        courseDoc.setChargeName(charge);
        // 调用feign接口方法保存到es中
        courseEsService.saveCourseEs(courseDoc);


        // 根据课程id查询对应的收藏用户
        Long courseTypeId = course.getCourseTypeId();
        // 根据类型id来查询收藏表里面是否有对象
        EntityWrapper<CourseCollect> wrapper = new EntityWrapper<>();
        wrapper.eq("course_type_id",courseTypeId);
        List<CourseCollect> courseCollects = courseCollectService.selectList(wrapper);
        // 断言对象集合不为null
        AssertUtil.isNotNull(courseCollects,GlobalErrorCode.COURSECOLLECT_ERROR);

        // 将遍历出来的userid放入一个集合中
        ArrayList<Long> courseCollects1 = new ArrayList<>();
        for (CourseCollect courseCollect : courseCollects) {
            Long userId = courseCollect.getUserId();
            courseCollects1.add(userId);
        }
        List<User> users = userService.listByIds(courseCollects1);
        if (users == null){
            return;
        }
        ArrayList<UserSmsDto> list = new ArrayList<>();
        for (User user1 : users) {
            UserSmsDto userSmsDto = new UserSmsDto(user1.getId(), user1.getPhone());
            list.add(userSmsDto);
        }
        // 发送短信，为收藏该类型课程的用户推送短信
        sendMessage(courseDoc,list);

    }

    @Override
    public void offLineCourse(Long id) {
        // 通过课程id查询course
        Course course = selectById(id);
        // 判断课程是否存在
        AssertUtil.isNotNull(course,GlobalErrorCode.COURSE_NULL_ERROR);
        // 修改状态
        course.setStatus(Course.down_status);
        updateById(course);
        // 从es索引库中删除
        courseEsService.delectCourseEs(id);

    }



//    private Course course;
//    private CourseMarket courseMarket;
//    private CourseDetail courseDetail;
//    private CourseSummary courseSummary;
//    private List<Teacher> teachers;
//    private List<CourseChapter> courseChapters;



    // 查询详情
    @Override
    public CourseDetailVo getDetail(Long courseId) {
        // 根据courseId查询course
        Course course = selectById(courseId);
        // 判断course是否为空
        AssertUtil.isNotNull(course,GlobalErrorCode.COURSE_NULL_ERROR);
        // 判断课程是否是上架状态
        boolean b1 =  course.getStatus() == Course.on_status;
        AssertUtil.isTrue(b1,GlobalErrorCode.COURSE_NULL_ERROR);
        // 根据courseId查询courseMarket对象
        CourseMarket courseMarket = courseMarketService.selectById(courseId);
        // 根据courseId查询courseDetail对象
        CourseDetail courseDetail = courseDetailService.selectById(courseId);
        // 根据courseId查询CourseSummary对象
        CourseSummary courseSummary = courseSummaryService.selectById(courseId);
        // 根据courseId查询老师集合
        List<Teacher> teachers = courseMapper.getTeacherByCourseId(courseId);
        // 查询课程章节对象
        EntityWrapper<CourseChapter> wrapper = new EntityWrapper<>();
        wrapper.eq("course_id",courseId);
        List<CourseChapter> courseChapters = courseChapterService.selectList(wrapper);

        Map<Long, CourseChapter> courseChapterMap = courseChapters.stream()
                .collect(Collectors.toMap(CourseChapter::getId, courseChapter -> courseChapter));
        // 根据courseid来查询mediafile 就是如此奇怪  你都
        JSONResult jsonResult = getMediaFileService.getMediaByCourseId(courseId);
        AssertUtil.isTrue(jsonResult.isSuccess(),GlobalErrorCode.ERROE);
        Object data = jsonResult.getData();
        AssertUtil.isNotNull(data, GlobalErrorCode.ERROE);
        // 获取该课程下所有的mediafile
        List<MediaFile> mediaFiles = JSON.parseArray(data.toString(), MediaFile.class);
        for (MediaFile mediaFile : mediaFiles) {
            mediaFile.setFileUrl("");
            CourseChapter courseChapter = courseChapterMap.get(mediaFile.getChapterId());
            if (courseChapter != null){
                courseChapter.getMediaFiles().add(mediaFile);
            }
        }

        return new CourseDetailVo(course, courseMarket, courseChapters, teachers, courseDetail, courseSummary);
    }
/*-------------------------------------------------------------------------------*/
    // 订单页面获取课程详情信息
    @Override
    public CourseInfoVo getinfo(String courseIds) {
        // 判断courseIds是否合法
        String[] split = courseIds.split(",");
        Stream<String> stream = Arrays.stream(split);
        // 判断是否为空字符串
        Stream<String> stringStream = stream.filter(id -> !StringUtils.isEmpty(id));
        // 转化为long类型
        Stream<Long> longStream = stringStream.map(id -> Long.valueOf(id));
        // 使用set进行去重处理
        Set<Long> collect = longStream.collect(Collectors.toSet());
        // 判断是否有非法参数
        boolean boo = collect.size() == courseIds.split(",").length;
        AssertUtil.isTrue(boo,GlobalErrorCode.ERROE);
        // 获取courseIds集合
        List<Long> courseIdsList = collect.stream().collect(Collectors.toList());
        // 获取课程对象
        List<Course> courses = selectBatchIds(courseIdsList);
        AssertUtil.isNotNull(courses,GlobalErrorCode.ERROE);
        // 查询courseMarkets对象
        List<CourseMarket> courseMarkets = courseMarketService.selectBatchIds(courseIdsList);
        // 将对象转化为map
        Map<Long, CourseMarket> map = courseMarkets.stream().collect(Collectors.toMap(CourseMarket::getId, courseMarket -> courseMarket));

        CourseInfoVo courseInfoVo = new CourseInfoVo();
        List<CourseOrderVo> courseOrderVos = new ArrayList<>();
        // 循环遍历courses
        for (Course course : courses) {
            CourseOrderVo courseOrderVo = new CourseOrderVo();
            boolean boo2 = course.getStatus()==1;
            AssertUtil.isTrue(boo2,GlobalErrorCode.COURSE_NO_ONLINE_ERROR);
            CourseMarket courseMarket = map.get(course.getId());
            AssertUtil.isNotNull(courseMarket, GlobalErrorCode.COURSE_MARKET_ERROR);
            courseOrderVo.setCourse(course);
            courseOrderVo.setCourseMarket(courseMarket);
            // 获取商品总价
            BigDecimal price = courseMarket.getPrice();
            BigDecimal decimal = courseInfoVo.getTotalAmount().add(price);
            courseInfoVo.setTotalAmount(decimal);
            // 将courseOrderVo对象添加到集合中
            courseOrderVos.add(courseOrderVo);
        }
        courseInfoVo.setCourseInfos(courseOrderVos);

        return courseInfoVo;
    }
/*-------------------------------------------------------------------------------*/
    private void sendMessage(CourseDoc courseDoc,List<UserSmsDto> list) {
        CourseSendMessageDto courseSendMessageDto = new CourseSendMessageDto();
        courseSendMessageDto.setTitle("课程发布消息");
        courseSendMessageDto.setContent("亲爱的用户您好，最新课程 <a href='localhost:6002/list.html?courseId="+courseDoc.getId()+"'> 测试 </a> 发布啦，点击课程了解详情");
        courseSendMessageDto.setUserSmsDtos(list);

        System.out.println(list);
        System.out.println(courseSendMessageDto);
        rocketMQTemplate.sendOneWay("topic-send-message:tag-send-message",
                JSON.toJSONString(courseSendMessageDto));
    }

    private Long add(Course course,List<Long> teacharIds) {
        course.setStatus(Course.down_status);
        course.setLoginId(3L);
        course.setLoginUserName("13330964748");
        String collect = teacherService.selectBatchIds(teacharIds).
                stream().map(teacher -> teacher.getName()).collect(Collectors.joining(","));
        course.setTeacherNames(collect);
        insert(course);

        return course.getId();
    }

    private Course selectByName(String name) {
        EntityWrapper<Course> wrapper = new EntityWrapper<>();
        wrapper.eq("name",name);
        Course course = selectOne(wrapper);
        return course;
    }
}
